/**
 * Created by Administrator on 2018/8/22.
 */
/*工具类*/

class MUntilS{
    request(param){
        return new Promise((resolve,reject)=>{
            $.ajax({
                url      : param.url || '',
                type     : param.type || 'get',
                dataType : param.dataType || 'json',
                data     : param.data || null,
                success  : res => {
                    //请求成功
                    if(res.status===0){
                        typeof resolve == 'function' && resolve(res.data,res.msg)
                    }
                    //没有登陆状态
                    else if(res.status===10){
                        //做登陆
                        this.doLogin();
                    }else{
                        //fail
                        typeof reject == 'function' && reject(res.msg || res.data)
                    }
                },
                error: err =>{
                    typeof reject == 'function' && reject(err.statusText)
                }
            })
        })

    }
    //跳转登陆
    doLogin(){
        window.location.href = '/login?redirect='+encodeURIComponent(window.location.pathname);
    }
    //获取URL参数
    getUrlParam(name){
        //xxxx.com ? param=www&param1=111
        let queryString = window.location.search.split('?')[1] || '',
            reg = new RegExp("(^|&)"+name+"=([^&]*)(&|$)"),
            result = queryString.match(reg);
        return result ? decodeURIComponent(result[2]) : null;
    }
    //错误提示
    errorTips(errMsg){
        alert(errMsg || '哎呀-出错了~~')
    }
    //本地存储
    setStorage(name,data){
        let dataType = typeof data;
        if (dataType==='object'){
            window.localStorage.setItem(name,JSON.stringify(data));
        }
        else if(
            ['number','string','boolean'].indexOf(dataType) >= 0
        ){
            window.localStorage.setItem(name,data);
        }else{
                alert('该类型不能用于本地存储...')
        }

    }
    //
    getStorage(name){
        let data = window.localStorage.getItem(name);
        if(data){
            return JSON.parse(data)
        }else{
            return ''
        }
    }
    //删除本地存储
    removeStorage(name){
        window.localStorage.removeItem(name);
    }
}
export default MUntilS;
